package com.abc.recycling.service.impl;

import com.abc.recycling.model.Notification;
import com.abc.recycling.model.NotificationTemplate;
import com.abc.recycling.mapper.NotificationMapper;
import com.abc.recycling.mapper.NotificationTemplateMapper;
import com.abc.recycling.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {

    private final NotificationMapper notificationMapper;
    private final NotificationTemplateMapper templateMapper;

    @Override
    @Transactional
    public void createSystemNotification(String title, String content, String receiverType) {
        try {
            log.info("创建系统通知: {}", title);
            Notification notification = new Notification();
            notification.setTitle(title);
            notification.setContent(content);
            notification.setType("SYSTEM");
            notification.setReceiverType(receiverType);
            notification.setCreateTime(LocalDateTime.now());
            
            notificationMapper.insert(notification);
            log.debug("系统通知创建成功: {}", notification.getId());
        } catch (Exception e) {
            log.error("创建系统通知失败: {}", e.getMessage());
            throw e;
        }
    }

    @Override
    @Transactional
    public void createUserNotification(String title, String content, Long receiverId) {
        try {
            log.info("创建用户通知: {}, 接收者ID: {}", title, receiverId);
            Notification notification = new Notification();
            notification.setTitle(title);
            notification.setContent(content);
            notification.setType("USER");
            notification.setReceiverId(receiverId);
            notification.setCreateTime(LocalDateTime.now());
            
            notificationMapper.insert(notification);
            log.debug("用户通知创建成功: {}", notification.getId());
        } catch (Exception e) {
            log.error("创建用户通知失败: {}", e.getMessage());
            throw e;
        }
    }

    @Override
    @Transactional
    public void createNotificationFromTemplate(String templateCode, Map<String, String> params, Long receiverId) {
        NotificationTemplate template = templateMapper.findByCode(templateCode);
        if (template == null) {
            throw new RuntimeException("消息模板不存在");
        }
        
        String title = replaceParams(template.getTitle(), params);
        String content = replaceParams(template.getContent(), params);
        
        Notification notification = new Notification();
        notification.setTitle(title);
        notification.setContent(content);
        notification.setType(template.getType());
        notification.setReceiverId(receiverId);
        notification.setCreateTime(LocalDateTime.now());
        
        notificationMapper.insert(notification);
    }

    @Override
    @Transactional
    public void sendNotification(Long notificationId) {
        Notification notification = notificationMapper.findById(notificationId);
        if (notification == null) {
            throw new RuntimeException("消息不存在");
        }
        
        notification.setIsSent(1);
        notification.setSendTime(LocalDateTime.now());
        notificationMapper.update(notification);
    }

    @Override
    @Transactional
    public void sendNotifications(List<Long> notificationIds) {
        for (Long id : notificationIds) {
            sendNotification(id);
        }
    }

    @Override
    @Transactional
    public void markAsRead(Long notificationId) {
        Notification notification = notificationMapper.findById(notificationId);
        if (notification == null) {
            throw new RuntimeException("消息不存在");
        }
        
        notification.setStatus(1);
        notification.setReadTime(LocalDateTime.now());
        notificationMapper.update(notification);
    }

    @Override
    public long countUnreadNotifications(Long userId) {
        return notificationMapper.countUnreadByUserId(userId);
    }

    @Override
    public List<Notification> getUserNotifications(Long userId) {
        return notificationMapper.findByUserId(userId);
    }

    @Override
    public List<Notification> getSystemNotifications() {
        return notificationMapper.findSystemNotifications();
    }

    @Override
    @Transactional
    public void createTemplate(NotificationTemplate template) {
        template.setCreateTime(LocalDateTime.now());
        templateMapper.insert(template);
    }

    @Override
    @Transactional
    public void updateTemplate(NotificationTemplate template) {
        NotificationTemplate existingTemplate = templateMapper.findById(template.getId());
        if (existingTemplate == null) {
            throw new RuntimeException("模板不存在");
        }
        
        template.setUpdateTime(LocalDateTime.now());
        templateMapper.update(template);
    }

    @Override
    @Transactional
    public void deleteTemplate(Long templateId) {
        templateMapper.deleteById(templateId);
    }

    @Override
    public List<NotificationTemplate> getAllTemplates() {
        return templateMapper.findAll();
    }

    @Override
    public NotificationTemplate getTemplateByCode(String templateCode) {
        return templateMapper.findByCode(templateCode);
    }

    @Override
    @Transactional
    public void deleteNotification(Long notificationId) {
        Notification notification = notificationMapper.findById(notificationId);
        if (notification == null) {
            throw new RuntimeException("通知不存在");
        }
        notificationMapper.deleteById(notificationId);
    }

    @Override
    public NotificationTemplate getTemplateById(Long templateId) {
        return templateMapper.findById(templateId);
    }

    @Override
    @Transactional
    public void updateTemplateStatus(Long templateId, Integer status) {
        NotificationTemplate template = templateMapper.findById(templateId);
        if (template == null) {
            throw new RuntimeException("模板不存在");
        }
        template.setStatus(status);
        template.setUpdateTime(LocalDateTime.now());
        templateMapper.update(template);
    }

    /**
     * 替换模板中的参数
     */
    private String replaceParams(String template, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return template;
        }
        
        Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
        Matcher matcher = pattern.matcher(template);
        
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String key = matcher.group(1).trim();
            String value = params.getOrDefault(key, matcher.group());
            matcher.appendReplacement(sb, value);
        }
        matcher.appendTail(sb);
        
        return sb.toString();
    }
} 